#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <unistd.h>
#include <netdb.h>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <cerrno>

#define BUFFER_SIZE 1024
#define PORT 8127
#define MSG "hello"

int main(int argc, char * argv[])
{
  char buffer[ BUFFER_SIZE ];
  
  int mainSocket, n;
  struct sockaddr_in serverStruct;
  struct hostent *hp;
  
  unsigned short port;
  
  if (argc > 1)
    port = (unsigned short)atoi(argv[1]);
  else {
    printf("Using default port value: %d\n", PORT);
    port = PORT; 
  } 
  
  
  mainSocket = socket(PF_INET, SOCK_STREAM, 0);
  
  if (mainSocket < 0) {
    perror("socket()");
    exit(1);
  }
  
  serverStruct.sin_family = PF_INET;
  
  hp = gethostbyname("monica.cs.rpi.edu");
  if (hp == NULL) {
    perror("Unknown host");
    exit(1);
  }
  
  bcopy((char *)hp->h_addr, (char *)&serverStruct.sin_addr, hp->h_length);
  serverStruct.sin_port = htons(port);
  
  int conResult = connect(mainSocket, (struct sockaddr *)&serverStruct, sizeof(serverStruct));
  
  if (conResult < 0) {
    perror("connect()");
    printf("Error Code: %d\n", errno);
    exit(1);
  }
  
  n = write(mainSocket, MSG, strlen(MSG));
  if (n < strlen(MSG)) {
    perror("write()");
    exit(1);
  }
  
  n = read(mainSocket, buffer, BUFFER_SIZE);
  if (n < 1) {
    perror("read()");
    exit(1);
  }
  else {
    buffer[n] = '\0';
    printf("Received message from server: %s\n", buffer);
  }
  
  close(mainSocket);
  
  return 0;
}
